import { useState, useEffect } from 'react'
import { View, Text } from '@tarojs/components'
import { Tabs, Radio, Button, DatetimePicker, Popup, Input } from '@taroify/core'
import { ClockOutlined } from '@taroify/icons'
import Taro, { useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import './index.scss'

// 获取当前主题
const getCurrentTheme = () => {
  try {
    const savedTheme = Taro.getStorageSync('user-theme-preference')
    if (savedTheme && (savedTheme === 'mint' || savedTheme === 'cream')) {
      return savedTheme
    }
    return 'mint' // 默认主题
  } catch (error) {
    console.error('读取主题偏好出错', error)
    return 'mint'
  }
}

const DateCalculator = () => {
  const [currentTheme, setCurrentTheme] = useState('mint')
  const [activeTab, setActiveTab] = useState(0)
  const [date1, setDate1] = useState(new Date())
  const [date2, setDate2] = useState(new Date())
  const [dateDiffResult, setDateDiffResult] = useState(null)
  const [dateDiffUnit, setDateDiffUnit] = useState('days')

  const [baseDate, setBaseDate] = useState(new Date())
  const [dateChangeValue, setDateChangeValue] = useState('')
  const [dateChangeUnit, setDateChangeUnit] = useState('days')
  const [dateChangeOperation, setDateChangeOperation] = useState('add')
  const [dateChangeResult, setDateChangeResult] = useState(null)

  const [showDatePicker1, setShowDatePicker1] = useState(false)
  const [showDatePicker2, setShowDatePicker2] = useState(false)
  const [showBaseDatePicker, setShowBaseDatePicker] = useState(false)

  // 监听主题变化
  useEffect(() => {
    const theme = getCurrentTheme()
    setCurrentTheme(theme)
  }, [])

  // 分享给朋友
  useShareAppMessage(() => {
    return {
      title: '日期计算从此简单！这个日期计算器让你精确掌握时间⏱️',
      path: '/pages/date-calculator/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png' // 可以添加分享图片URL
    }
  })

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: '日期计算从此简单！这个日期计算器让你精确掌握时间⏱️',
      query: '',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png' // 可以添加分享图片URL
    }
  })

  const handleBack = () => {
    Taro.navigateBack()
  }

  const formatDate = (date) => {
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  // 计算两个日期之间的差异
  const calculateDateDifference = () => {
    const d1 = new Date(date1)
    const d2 = new Date(date2)

    const diffTime = Math.abs(d2 - d1)
    let result = 0

    switch (dateDiffUnit) {
      case 'days':
        result = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
        break
      case 'weeks':
        result = Math.ceil(diffTime / (1000 * 60 * 60 * 24 * 7))
        break
      case 'months': {
        // 简化的月份计算
        const monthDiff = (d2.getFullYear() - d1.getFullYear()) * 12 + d2.getMonth() - d1.getMonth()
        result = Math.abs(monthDiff)
        break
      }
      case 'years':
        // 简化的年份计算
        result = Math.abs(d2.getFullYear() - d1.getFullYear())
        break
      default:
        result = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    }

    setDateDiffResult(result)
  }

  // 添加或减去天数/月份/年份
  const calculateDateChange = () => {
    if (!dateChangeValue || Number.isNaN(Number(dateChangeValue)) || dateChangeValue <= 0) {
      Taro.showToast({
        title: '请输入有效的数值',
        icon: 'none'
      })
      return
    }

    const d = new Date(baseDate)
    const value = parseInt(dateChangeValue)

    if (dateChangeOperation === 'add') {
      switch (dateChangeUnit) {
        case 'days':
          d.setDate(d.getDate() + value)
          break
        case 'weeks':
          d.setDate(d.getDate() + value * 7)
          break
        case 'months':
          d.setMonth(d.getMonth() + value)
          break
        case 'years':
          d.setFullYear(d.getFullYear() + value)
          break
      }
    } else {
      switch (dateChangeUnit) {
        case 'days':
          d.setDate(d.getDate() - value)
          break
        case 'weeks':
          d.setDate(d.getDate() - value * 7)
          break
        case 'months':
          d.setMonth(d.getMonth() - value)
          break
        case 'years':
          d.setFullYear(d.getFullYear() - value)
          break
      }
    }

    setDateChangeResult(d)
  }

  return (
    <View className={`date-calculator theme-${currentTheme}`}>
      <View className='converter-header'>
        <Text className='header-title'>日期计算器</Text>
      </View>
      <Tabs value={activeTab} onChange={setActiveTab}>
        <Tabs.TabPane title='日期差异' />
        <Tabs.TabPane title='日期计算' />
      </Tabs>

      {activeTab === 0 ? (
        <View className='tab-content'>
          <View className='group-container'>
            <View className='group-title'>选择日期</View>
            <View className='cell-container'>
              <View className='cell-title'>第一个日期</View>
              <View className='cell-value' onClick={() => setShowDatePicker1(true)}>
                <Text className='date-value'>{formatDate(date1)}</Text>
                <ClockOutlined />
              </View>
            </View>
            <View className='cell-container'>
              <View className='cell-title'>第二个日期</View>
              <View className='cell-value' onClick={() => setShowDatePicker2(true)}>
                <Text className='date-value'>{formatDate(date2)}</Text>
                <ClockOutlined />
              </View>
            </View>

            <View className='cell-container'>
              <View className='cell-title'>计算单位</View>
              <View className='cell-value'>
                <Radio.Group defaultValue={dateDiffUnit} value={dateDiffUnit} onChange={setDateDiffUnit}>
                  <Radio style={{ marginRight: '8px' }} name='days'>
                    天
                  </Radio>
                  <Radio style={{ marginRight: '8px' }} name='weeks'>
                    周
                  </Radio>
                  <Radio style={{ marginRight: '8px' }} name='months'>
                    月
                  </Radio>
                  <Radio style={{ marginRight: '8px' }} name='years'>
                    年
                  </Radio>
                </Radio.Group>
              </View>
            </View>
          </View>

          <View className='button-container'>
            <Button color='primary' block onClick={calculateDateDifference}>
              计算日期差异
            </Button>
          </View>

          {dateDiffResult !== null && (
            <View className='group-container'>
              <View className='group-title'>计算结果</View>
              <View className='cell-container'>
                <View className='result-content'>
                  <Text className='result-label'>
                    {formatDate(date1)} 和 {formatDate(date2)} 之间相差：
                  </Text>
                  <View className='result-value-container'>
                    <Text className='result-value'>
                      {dateDiffResult}{' '}
                      {dateDiffUnit === 'days'
                        ? '天'
                        : dateDiffUnit === 'weeks'
                        ? '周'
                        : dateDiffUnit === 'months'
                        ? '个月'
                        : '年'}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          )}
        </View>
      ) : (
        <View className='tab-content'>
          <View className='group-container'>
            <View className='group-title'>日期计算</View>
            <View className='cell-container'>
              <View className='cell-title'>基准日期</View>
              <View className='cell-value' onClick={() => setShowBaseDatePicker(true)}>
                <Text className='date-value'>{formatDate(baseDate)}</Text>
                <ClockOutlined />
              </View>
            </View>

            <View className='cell-container'>
              <View className='cell-title'>操作</View>
              <View className='cell-value'>
                <Radio.Group
                  defaultValue={dateChangeOperation}
                  value={dateChangeOperation}
                  onChange={setDateChangeOperation}>
                  <Radio style={{ marginRight: '8px' }} name='add'>
                    增加
                  </Radio>
                  <Radio style={{ marginRight: '8px' }} name='subtract'>
                    减少
                  </Radio>
                </Radio.Group>
              </View>
            </View>

            <View className='cell-container'>
              <View className='cell-title'>数值</View>
              <View className='cell-value'>
                <Input
                  type='number'
                  placeholder='请输入数值'
                  value={dateChangeValue}
                  onChange={(e) => setDateChangeValue(e.detail.value)}
                />
              </View>
            </View>

            <View className='cell-container'>
              <View className='cell-title'>单位</View>
              <View className='cell-value'>
                <Radio.Group defaultValue={dateChangeUnit} value={dateChangeUnit} onChange={setDateChangeUnit}>
                  <Radio style={{ marginRight: '8px' }} name='days'>
                    天
                  </Radio>
                  <Radio style={{ marginRight: '8px' }} name='weeks'>
                    周
                  </Radio>
                  <Radio style={{ marginRight: '8px' }} name='months'>
                    月
                  </Radio>
                  <Radio style={{ marginRight: '8px' }} name='years'>
                    年
                  </Radio>
                </Radio.Group>
              </View>
            </View>
          </View>

          <View className='button-container'>
            <Button color='primary' block onClick={calculateDateChange}>
              计算结果日期
            </Button>
          </View>

          {dateChangeResult && (
            <View className='group-container'>
              <View className='group-title'>计算结果</View>
              <View className='cell-container'>
                <View className='result-content'>
                  <Text className='result-label'>
                    {dateChangeOperation === 'add' ? '增加' : '减少'} {dateChangeValue}{' '}
                    {dateChangeUnit === 'days'
                      ? '天'
                      : dateChangeUnit === 'weeks'
                      ? '周'
                      : dateChangeUnit === 'months'
                      ? '个月'
                      : '年'}{' '}
                    后的日期：
                  </Text>
                  <View className='result-value-container'>
                    <Text className='result-value'>{formatDate(dateChangeResult)}</Text>
                  </View>
                </View>
              </View>
            </View>
          )}
        </View>
      )}

      {/* 日期选择器弹窗 */}
      <Popup
        open={showDatePicker1}
        style={{ width: '80%' }}
        rounded
        position='bottom'
        onClose={() => setShowDatePicker1(false)}>
        <DatetimePicker
          type='date'
          value={date1}
          onChange={setDate1}
          formatter={(type, val) => {
            if (type === 'year') {
              return `${val}年`
            }
            if (type === 'month') {
              return `${val}月`
            }
            if (type === 'day') {
              return `${val}日`
            }
            return val
          }}>
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button onClick={() => setShowDatePicker1(false)}>取消</DatetimePicker.Button>
            <DatetimePicker.Title>选择日期</DatetimePicker.Title>
            <DatetimePicker.Button onClick={() => setShowDatePicker1(false)}>确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
      </Popup>

      <Popup open={showDatePicker2} rounded position='bottom' onClose={() => setShowDatePicker2(false)}>
        <DatetimePicker
          type='date'
          value={date2}
          onChange={setDate2}
          formatter={(type, val) => {
            if (type === 'year') {
              return `${val}年`
            }
            if (type === 'month') {
              return `${val}月`
            }
            if (type === 'day') {
              return `${val}日`
            }
            return val
          }}>
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button onClick={() => setShowDatePicker2(false)}>取消</DatetimePicker.Button>
            <DatetimePicker.Title>选择日期</DatetimePicker.Title>
            <DatetimePicker.Button onClick={() => setShowDatePicker2(false)}>确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
      </Popup>

      <Popup open={showBaseDatePicker} rounded position='bottom' onClose={() => setShowBaseDatePicker(false)}>
        <DatetimePicker
          type='date'
          value={baseDate}
          onChange={setBaseDate}
          formatter={(type, val) => {
            if (type === 'year') {
              return `${val}年`
            }
            if (type === 'month') {
              return `${val}月`
            }
            if (type === 'day') {
              return `${val}日`
            }
            return val
          }}>
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button onClick={() => setShowBaseDatePicker(false)}>取消</DatetimePicker.Button>
            <DatetimePicker.Title>选择日期</DatetimePicker.Title>
            <DatetimePicker.Button onClick={() => setShowBaseDatePicker(false)}>确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
      </Popup>
    </View>
  )
}

export default DateCalculator
